<template>
	<view class="container">
		<!-- 空白页 -->
		<view v-if="!isLogin || empty===true" class="empty">
			<image src="/static/img/emptyCart.jpg" mode="aspectFit"></image>
			<view v-if="isLogin" class="empty-tips">
				空空如也
				<navigator class="navigator" v-if="isLogin" url="../index/index" open-type="switchTab">随便逛逛></navigator>
			</view>
			<view v-else class="empty-tips">
				空空如也
				<view class="navigator" @click="navToLogin">去登陆></view>
			</view>
		</view>
		<view v-else>
			<!-- 列表 -->
			<view class="cart-list">
				<block v-for="(item, index) in cartList" :key="item.id">
					<view
						class="cart-item" 
						:class="{'b-b': index!==cartList.length-1}"
					>
						<view class="image-wrapper">
							<image :src="item.images" 
								:class="[item.loaded]"
								mode="aspectFill"
								lazy-load 
								@load="onImageLoad('cartList', index)" 
								@error="onImageError('cartList', index)"
							></image>
							<view 
								class="iconfont icon-xuanzhong checkbox"
								:class="{checked: item.checked}"
								@click="check('item', index)"
							></view>
						</view>
						<view class="item-right">
							<text class="ellipsis title">{{item.title}}</text>
							<view class="attr">
								<text v-for="(sItem,sIndex) in item.spec" :key="sIndex">{{sItem.type}}:{{sItem.value}}</text>
							</view>
							<text class="price">¥{{item.price}}</text>
							<uni-number-box
								class="step"
								:min="1" 
								:max="parseInt(item.inventory)"
								:value="parseInt(item.inventory)>parseInt(item.stock)?parseInt(item.stock):parseInt(item.inventory)"
								:isMax="parseInt(item.inventory)>=parseInt(item.stock)?true:false"
								:isMin="parseInt(item.inventory)===1"
								:index="index"
								@eventChange="numberChange"
							></uni-number-box>
						</view>
						<text class="del-btn iconfont icon-shanchu" @click="deleteCartItem(item.id,index)"></text>
					</view>
				</block>
			</view>
			<!-- 底部菜单栏 -->
			<view class="action-section">
				<view class="checkbox">
					<image 
						:src="allChecked?'/static/icon/selected.png':'/static/icon/select.png'" 
						mode="aspectFit"
						@click="check('all')"
					></image>
					<view class="clear-btn" :class="{show: allChecked}" @click="clearCart">
						清空
					</view>
				</view>
				<view class="total-box">
					<text class="price">¥{{total}}</text>
					<text class="coupon">
						应支付总金额：
						<text>{{total}}</text>
						元
					</text>
				</view>
				<button type="primary" class="no-border confirm-btn" @click="createOrder">去结算</button>
			</view>
		</view>
	</view>
</template>

<script>
	import uniNumberBox from '@/components/uni-number-box.vue'
	export default {
		components: {
			uniNumberBox
		},
		data() {
			return {
				userInfo:[],
				isLogin:false,
				total: 0, //总价格
				allChecked: false, //全选状态  true|false
				delShow:false, //显示删除按钮
				empty: false, //空白页现实  true|false
				cartList: [],
			};
		},
		onShow(){
			// 清除这个缓存数据，以便客户从createOrder页面返回cart，数据不更新。
			uni.removeStorageSync('goodsData');
			
			this.loadData();
			this.userInfo=uni.getStorageSync('gUserInfo');
			 
			
			// 更改登录状态
			if(this.userInfo){
				this.isLogin = true;
			}else{
				this.isLogin=false;
				this.userInfo=[];
			}
		},
		watch:{
			//显示空白页
			cartList(e){
				let empty = e.length === 0 ? true: false;
				if(this.empty !== empty){
					this.empty = empty;
				}
			}
		},
		methods: {
			//请求购物车数据
			loadData(){
				let self=this;
				let cartListUrl=this.requestUrl.cartList;
				this.util.request(cartListUrl,'post',function(res){
					if(res.data.code==0 && res.data.data){
						self.cartList=res.data.data.data;
					}
				})
				this.calcTotal();  //计算总价
			},
			//监听image加载完成
			onImageLoad(key, index) {
				this.$set(this[key][index], 'loaded', 'loaded');
			},
			//监听image加载失败
			onImageError(key, index) {
				this[key][index].images = '/static/errorImage.jpg';
			},
			navToLogin(){
				uni.navigateTo({
					url: '/pages/member/login'
				})
			},
			//选中状态处理
			check(type, index){
				if(type === 'item'){
					this.cartList[index].checked = !this.cartList[index].checked;
				}else{
					const checked = !this.allChecked
					const list = this.cartList;
					list.forEach(item=>{
						item.checked = checked;
					})
					this.allChecked = checked;
				}
				this.calcTotal(type);
			},
			//数量
			numberChange(data){
				this.cartList[data.index].stock = data.number;
				let list=this.cartList;
				let saveStockUrl=this.requestUrl.saveStock;
				let params={
					data:{
						id:list[data.index].id, //购物车数据id
						goods_id:list[data.index].goods_id, //购物车商品id
						stock:list[data.index].stock //要保存的数量
					}
				}
				this.util.request(saveStockUrl,'post',function(res){
					// 更新不成功，输出错误
					if(res.data.code !== 0){
						uni.showToast({
							title: res.data.msg,
							duration:1500
						});
					}
		
				},params);
				this.calcTotal();
			},
			
			//删除 ids要删除的id 字符串 
			//start 是处理cartList数组,删除元素的起始位置，默认从第一个开始删
			//length 是处理cartList数组，要删除的元素个数，默认删除一个
			deleteCartItem(ids,start=0,length=1){
				let self=this;
				let cartDelUrl=this.requestUrl.cartDel;
				let params={
					data:{
						id:ids
					}
				};
				this.util.request(cartDelUrl,'post',function(res){
					if(res.data.code==0){
						self.cartList.splice(start, length);
						uni.showToast({
							title: res.data.msg,
							duration: 1500,
						});
					}else{
						uni.showToast({
							title: res.data.msg,
							image:'/static/icon/error.png',
							duration: 1500,
						});
					}
				},params);
				this.calcTotal();
			},
			//清空购物车
			clearCart(){
				uni.showModal({
					content: '清空购物车？',
					success: (e)=>{
						if(e.confirm){
							const list = this.cartList;
							let ids='';
							list.forEach(item=>{
								if(item.checked==true){
									ids +=item.id + ',';
								}
							})
							// 去掉字符串最后的 ','
							ids=ids.substring(0,ids.length-1);
							this.deleteCartItem(ids,0,list.length);
						}
					}
				})
			},
			//计算总价
			calcTotal(){
				let list = this.cartList;
				if(list.length === 0){
					this.empty = true;
					return;
				}
				let total = 0;
				let checked = true;
				list.forEach(item=>{
					if(item.checked === true){
						total += item.price * parseInt(item.stock);
					}else if(checked === true){
						checked = false;
					}
				})
				this.allChecked = checked;
				this.total = Number(total.toFixed(2));
			},
			//创建订单
			createOrder(){
				let list = this.cartList;
				
				let ids='';
				list.forEach(item=>{
					if(item.checked){
						ids +=item.id + ',';
					}
				})
				// 去掉字符串最后的 ','
				ids=ids.substring(0,ids.length-1);
				if(ids!==''){
					let goodsData={
						buy_type:'cart',
						ids:ids
					};
					uni.navigateTo({
						url: `/pages/order/createOrder?goodsData=${JSON.stringify({goodsData})}`
					})
				}else{
					uni.showToast({
						title: '未选择商品',
						image:'/static/icon/error.png',
						duration:1500
					});
				}
			}
		}
	}
</script>

<style lang='scss'>
	.container{
		padding-bottom: 134upx;
		/* 空白页 */
		.empty{
			position:fixed;
			left: 0;
			top:0;
			width: 100%;
			height: 100vh;
			padding-bottom:100upx;
			display:flex;
			justify-content: center;
			flex-direction: column;
			align-items:center;
			background: #fff;
			image{
				width: 240upx;
				height: 160upx;
				margin-bottom:30upx;
			}
			.empty-tips{
				display:flex;
				font-size: $uni-font-size-sm+2upx;
				color: $uni-text-color-disable;
				.navigator{
					color: $uni-color-primary;
					margin-left: 16upx;
				}
			}
		}
	}
	/* 购物车列表项 */
	.cart-item{
		display:flex;
		position:relative;
		padding:30upx 40upx;
		.image-wrapper{
			width: 230upx;
			height: 230upx;
			flex-shrink: 0;
			position:relative;
			image{
				border-radius:16upx;
				height: 100%;
			}
		}
		.checkbox{
			position:absolute;
			left:-16upx;
			top: -16upx;
			z-index: 8;
			font-size: 44upx;
			line-height: 1;
			padding: 4upx;
			color: $uni-text-color-disable;
			background:#fff;
			border-radius: 50px;
		}
		.item-right{
			display:flex;
			flex-direction: column;
			flex: 1;
			overflow: hidden;
			position:relative;
			padding-left: 30upx;
			.title,.price{
				font-size:$uni-text-color + 2upx;
				color: $uni-text-color;
				height: 40upx;
				line-height: 40upx;
			}
			.attr{
				font-size: $uni-font-size-sm + 2upx;
				color: $uni-text-color-grey;
				height: 50upx;
				line-height: 50upx;
				text{
					margin-right: 20rpx;
				}
			}
			.price{
				height: 50upx;
				line-height:50upx;
			}
		}
		.del-btn{
			padding:4upx 0upx 0 20rpx;
			font-size:36upx; 
			height: 50upx;
			color: $uni-text-color-zhu;
		}
	}
	/* 底部栏 */
	.action-section{
		/* #ifdef H5 */
		margin-bottom:100upx;
		/* #endif */
		position:fixed;
		left: 30upx;
		bottom:30upx;
		z-index: 95;
		display: flex;
		align-items: center;
		width: 690upx;
		height: 100upx;
		padding: 0 30upx;
		background: rgba(255,255,255,.9);
		box-shadow: 0 0 20upx 0 rgba(0,0,0,.5);
		border-radius: 16upx;
		box-sizing: border-box;
		.checkbox{
			height:52upx;
			position:relative;
			image{
				width: 52upx;
				height: 100%;
				position:relative;
				z-index: 5;
			}
		}
		.clear-btn{
			position:absolute;
			left: 26upx;
			top: 0;
			z-index: 4;
			width: 0;
			height: 52upx;
			line-height: 52upx;
			padding-left: 38upx;
			font-size: $uni-font-size-base;
			color: #fff;
			background: $uni-text-color-disable;
			border-radius:0 50px 50px 0;
			opacity: 0;
			transition: .2s;
			&.show{
				opacity: 1;
				width: 90upx;
			}
		}
		.total-box{
			flex: 1;
			display:flex;
			flex-direction: column;
			text-align:right;
			padding-right: 40upx;
			.price{
				font-size: $uni-font-size-lg;
				color:$uni-text-color-grey;
			}
			.coupon{
				font-size: $uni-font-size-sm;
				color:$uni-text-color;
				text{
					color: $uni-text-color-zhu;
				}
			}
		}
		.confirm-btn{
			padding: 0 38upx;
			margin: 0;
			border-radius: 100px;
			height: 76upx;
			line-height: 76upx;
			font-size: $uni-font-size-base + 2upx;
			background: $uni-bg-color-zhu;
			box-shadow: 1px 2px 5px rgba(217, 60, 93, 0.72)
		}
	}
	/* 复选框选中状态 */
	.action-section .checkbox.checked,
	.cart-item .checkbox.checked{
		color:$uni-bg-color-zhu;
	}
	.step{bottom:0}
</style>

